class Container {
  private services = new Map();

  add(token: string, Factory: any) {
    if (Factory.prototype && Factory.prototype.constructor === Factory) {
      // Factory is a constructor function
      this.services.set(token, new Factory());
    } else {
      // Factory is a regular function
      this.services.set(token, Factory());
    }
  }

  get(token: string) {
    return this.services.get(token);
  }
}

class CatsRepository {
  getCats() {
    return ['Cat 1', 'Cat 2', 'Cat 3'];
  }
}

class CatsService {
  constructor(private catsRepository: CatsRepository) {}

  getAllCats() {
    return this.catsRepository.getCats();
  }
}
// 创建了一个第三方容器实例
const container = new Container();
// 扫描系统中所有的服务，把这些服务都添加到容器里面，让容器来管理这些服务
container.add('CatsRepository', CatsRepository);
container.add(
  'CatsService',
  () => new CatsService(container.get('CatsRepository'))
);

// 要使用服务，直接从容器中拿就行了，依赖关系在初始化的时候已经处理好了
const catsService = container.get('CatsService');
console.log(catsService.getAllCats());
